<!--
*@Author: QWP
*@Description: 司机信息编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog v-bind="$attrs"
    :confirmLoading="formLoading"
    destroyOnClose
    @submit="submit"
    @close="dialogClose">
    <a-layout class="f-h-100">
      <a-layout-content class="s-bg-white"
        style="overflow: auto">
        <a-space  direction="vertical">
          <u-busi-card title=""
          :bordered="false">
            <u-form :elements="formEls"
              :model="form"
              :loading="formLoading"
              :gutter="16"
              @formChange="getUser"
              ref="formRef">
            </u-form>
          </u-busi-card>
        </a-space>
      </a-layout-content>
    </a-layout>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue' 
import { useLoginStore,  useBaseStore } from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { HomeOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { TreeProps } from 'ant-design-vue/es/vc-tree';
import { ColumnProps } from 'ant-design-vue/es/table';
import { _IColumnProps } from '@/components/common/tableEdit/interface.ts'
import { fileCols } from '@/common/model/fileCols'
import { regions, depts, users, isSel } from '@/common/model/base'
import { storeToRefs } from 'pinia';
import * as driverApi from '@/service/administration/driver'
import * as userApi from '@/service/system/user'
import * as deptApi from '@/service/system/dept'
import { messageC, alertC, numberC } from '@/util/common';
interface Props {
  keyid?: string
}
const props = defineProps<Props>()
const attrs = useAttrs()
const emits = defineEmits(['success'])

const { userInfo } = storeToRefs(useLoginStore())
const { APPROVEDMODEL, deptData, deptUsers } = storeToRefs(useBaseStore())

// 基础数据
const baseData = reactive({
  cpdata: [],
})

// 部门下的人员数据
const deptUserData = computed(() => {
  let dept = (deptUsers.value ?? []).find(i => i.keyid == form.value['ssdeptid']);
  return dept ? (dept['children'] ?? []) : []
})

// 表单信息
const formLoading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref({})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '80px',
  colon: false
}
const formEls: Array<_IFormEl> = reactive([
  { label: '所属部门', key: 'ssdeptid', col: { span:24,}, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: deptData.value, fieldNames: { label: 'name', value: 'keyid' } },
  },
  { label: '执行司机', key: 'driverid', col: { span:24 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: deptUserData, fieldNames: { label: 'name', value: 'keyid' } }, 
  },
  { label: '准驾车型', key: 'approvedmodel', col: { span:24 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: APPROVEDMODEL.value}, 
  },
  { label: '车牌号', key: 'fkvehicleid', col: { span:24 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: computed(()  => baseData.cpdata), fieldNames: { label: 'platenumber', value: 'keyid' }}, 
  },
  { label: '司机电话', key: 'driverphone', col: { span:24 }, element: 'input', 
    formItemProps: { ...formItemProps, required: true,
      rules: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码!', trigger: 'change' }
    },
    componentProps: {
      placeholder: '请输入手机联系电话', maxLength: 11, showCount: true
    }
  },
  { label: '入职时间', key: 'entrydate', col: { span:24 }, element: 'datepicker', 
    formItemProps: { ...formItemProps, },
  },
  { label: '工资卡号', key: 'paycard', col: { span:24 }, element: 'input', 
    formItemProps: { ...formItemProps,
      rules: { pattern: /\d+/g, message: '请输入正确的工资卡号!', trigger: 'change' }
    },
    componentProps: { showCount: true }
  },
  { label: '公务卡号', key: 'businesscard', col: { span:24 }, element: 'input', 
    formItemProps: { ...formItemProps,
      rules: { pattern: /\d+/g, message: '请输入正确的公务卡号!', trigger: 'change' }
    },
    componentProps: { showCount: true }
  },
])

// 初始化表单数据
const initFormValue = () => {
  form.value.fkuserid= userInfo.value["userId"];
  form.value.fkusername= userInfo.value["name"];
  form.value.fkdeptid= userInfo.value["deptId"];
  form.value.redeptname= userInfo.value["deptName"];
  form.value.fkunitsid= userInfo.value["unitId"];
  form.value.unitName= userInfo.value["unitName"];
  form.value.ssdeptid= userInfo.value["deptId"];
  form.value.ssdeptname= userInfo.value["deptName"];
}

// 确认提交
const submit = async () => {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    if(error.errorFields.length != 0) {
      alertC(`${error.errorFields[0].errors[0]}`, "warning");
    } else {
      alertC("请将必填项填写完毕!", "warning");
    }
    return
  }
  
  formLoading.value = true;
  try {
    const url = form.value.keyid ? "update" : "add";
    const data = await driverApi[url](form.value);
    if (data.code == 0) {
      messageC(data.msg, "success");
      emits("success");
      dialogClose()
    } else {
      alertC(res.msg, "warning");
    }
  } catch (error) { }
  
  formLoading.value = false;
}

// c初始化车辆信息表单
const initFormEls = async () => {
  let elIndex = formEls.findIndex((i) => i.key == "ssdeptid");
  if (elIndex != -1) {
    let extra = userInfo.value["extra"] || {};
    let roles = extra["roles"] || {};
    let carRole = roles["6"] || [];
    formEls.splice(elIndex, 1, { ...formEls[elIndex], disabled: !carRole.some((i) => i.keyid == "1802538658906628097") });
  }
}

const getEnmu = async () => {
  getCarNum();
  getUser({ key: 'ssdeptid', value: form.value.ssdeptid });
}

// 获取车辆信息
const getCarNum = async () => {
  try {
    const data = await driverApi.selectPlateNumber2("type=1");
    if (data.code == 0) {
      baseData.cpdata = data.data;
    }
  } catch (error) {}
}

// 点击下拉框获取人员
const getUser = async ({ key, value }) => {
  if (key == "ssdeptid") {
    let b = deptData.value.find((item) => item.keyid == value);
    form.value.ssdeptname = b ? b.name : '';
  }
  // 选择用户自动回显下面的数据
  else if (key == "driverid") {
    let driverInfo = deptUserData.value.find((item) => item.keyid == value);
    if(driverInfo) {
      form.value.drivername = driverInfo.reusername;
      // form.value.entrydate = driverInfo['entrydate'] ?? '';
      let exa = driverInfo['exa'] ?? null;
      if(exa) {
        form.value.driverphone = exa.tel;
        form.value.paycard = exa.paycard;
        form.value.businesscard = exa.businesscard;
      }
    }
  }
  else if (key == "fkvehicleid") {
    form.value.platenumber = baseData.cpdata.find((item) => item.keyid == value).platenumber;
  }
}

// 回显
const getHxData = async() => {
  formLoading.value = true;
  try {
    const data = await driverApi.query(props.keyid)
    if (data.code == 0) {
      form.value = data.data || {}
      if(form.value['approvedmodel']) {
        form.value['approvedmodel'] = numberC(form.value['approvedmodel'])
        // form.value['approvedmodel'] += ''
      }
    }
  } catch (error) {}
  formLoading.value = false;
}

// 弹窗关闭
const dialogClose = () => {
  formRef.value.form.resetFields();
  form.value = {}
}

watch(() => attrs.open, (nval, oval) => {
  if (nval == true) {
    initFormValue();
    initFormEls();
    getEnmu();
    if (props.keyid != "") {
      form.value.keyid = props.keyid;
      getHxData();
    }
  }
})
</script>

<style lang='scss' >
</style>